package com.li.huffmantree;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import sun.font.DelegatingShape;

import java.net.PortUnreachableException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

//创建赫夫曼树
public class HuffmanTree {
    public static void main(String[] args) {
        int arr[] = {13, 7, 8, 3, 29, 6, 1};
        Node root = creat(arr);
        preOrder(root);


    }

    //前序遍历
    public static void preOrder(Node root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("是空值");
        }

    }


    public static Node creat(int[] arr) {
        List<Node> nodes = new ArrayList<Node>();
        for (int value : arr) {
            nodes.add(new Node(value));
        }
        while (nodes.size() > 1) {
            Collections.sort(nodes);
            //取出权值最小的节点
            Node left = nodes.get(0);
            Node right = nodes.get(1);
            Node parent = new Node(left.value + right.value);
            parent.left = left;
            parent.right = right;
            //arrlist处理
            nodes.remove(left);
            nodes.remove(right);
            //将parent加入到nodes
            nodes.add(parent);
        }
        return nodes.get(0);


    }
}

class Node implements Comparable<Node> {
    int value;
    Node left;
    Node right;

    //前序
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +

                '}';
    }

    public int compareTo(Node o) {
        return this.value - o.value;
    }
}